package com.vh.webapp.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Preparable;
import com.vh.model.Expense;

/**
 * Action for facilitating Expense Entry feature.
 */
public class ExpenseEntryAction extends BaseAction implements Preparable {
    private static final long serialVersionUID = 6776558938712115191L;
    private List<Expense> expenses;
    private Expense expense;
    
    public List<Expense> getExpenses() {
		return expenses;
	}

	public void setExpenses(List<Expense> expenses) {
		this.expenses = expenses;
	}

	public Expense getExpense() {
		return expense;
	}

	public void setExpense(Expense expense) {
		this.expense = expense;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	private String id;

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        /* prevent failures on new*/
        if (getRequest().getMethod().equalsIgnoreCase("post") && (!"".equals(getRequest().getParameter("expense.id")))) {
            expense = expenseManager.get(new Long(getRequest().getParameter("expense.id")));
        }else
        {
        	expense=new Expense();
        }
    }

    /**
     * Delete the user passed in.
     *
     * @return success
     */
    public String delete() {
        expenseManager.remove(expense.getId());
        List<Object> args = new ArrayList<Object>();
        args.add(expense.getDoe());
        saveMessage(getText("expense.deleted", args));

        return SUCCESS;
    }

    /**
     * Grab the user from the database based on the "id" passed in.
     *
     * @return success if user found
     * @throws IOException can happen when sending a "forbidden" from response.sendError()
     */
    public String edit() throws IOException {
        HttpServletRequest request = getRequest();
        boolean editProfile = (request.getRequestURI().indexOf("editProfile") > -1);

        // if URL is "editProfile" - make sure it's the current user
        if (editProfile && ((request.getParameter("id") != null) || (request.getParameter("from") != null))) {
            ServletActionContext.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
            log.warn("User '" + request.getRemoteUser() + "' is trying to edit user '" +
                    request.getParameter("id") + "'");
            return null;
        }
       
        return SUCCESS;
    }

    /**
     * Default: just returns "success"
     *
     * @return "success"
     */
    public String execute() {
        return SUCCESS;
    }

    /**
     * Sends users to "mainMenu" when !from.equals("list"). Sends everyone else to "cancel"
     *
     * @return "mainMenu" or "cancel"
     */
    public String cancel() {
        if (!"list".equals(from)) {
            return "mainMenu";
        }
        return "cancel";
    }

    /**
     * Save user
     *
     * @return success if everything worked, otherwise input
     * @throws Exception when setting "access denied" fails on response
     */
    public String save() throws Exception {

        //Integer originalVersion = expense.getVersion();

        boolean isNew = ("".equals(getRequest().getParameter("expense.version")));
        // only attempt to change roles if expense is admin
        // for other expenses, prepare() method will handle populating
        

        
        expenseManager.save(expense);
         
        if (!"list".equals(from)) {
            // add success messages
            saveMessage(getText("expense.saved"));
            return "mainMenu";
        } else {
            // add success messages
            List<Object> args = new ArrayList<Object>();
            args.add(expense.getDoe());
            if (isNew) {
                saveMessage(getText("expense.added", args));
                // Send an account information e-mail
                return SUCCESS;
            } else {
                saveMessage(getText("expense.updated", args));
                return INPUT;
            }
        }
    }

    /**
     * Fetch all users from database and put into local "users" variable for retrieval in the UI.
     *
     * @return "success" if no exceptions thrown
     */
    public String list() {
        expenses = expenseManager.getAll();
        return SUCCESS;
    }

}
